package com.tengfei.adapterdemo.adapter;

import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.bumptech.glide.signature.ObjectKey;
import com.tengfei.adapterdemo.R;

import java.util.HashMap;
import java.util.Map;


public class FrameworkAdapter extends BaseAdapter {

    private Map<String, Object> maps = new HashMap<>();


    public void setMap(Map<String, Object> maps) {
        this.maps = maps;
    }

    @Override
    public int getCount() {
        return (int) maps.get("img_count");
    }

    @Override
    public Object getItem(int i) {
        return (String) maps.get("url");
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View rootview = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_photo, null, true);
        ImageView imageview = rootview.findViewById(R.id.iv_2);
        // 加载图片
        Glide.with(viewGroup.getContext())
                .asBitmap()
                .load(getItem(i))
                .signature(new ObjectKey(String.valueOf(System.currentTimeMillis())))
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        int imageWidth = resource.getWidth();
                        int imageHeight = resource.getHeight();
                        // 获取实际屏幕宽度
                        int screenWidth = (int) maps.get("screenWidth");
                        int screenHeight = (int) ((float) imageHeight / imageWidth * screenWidth);
                        ViewGroup.LayoutParams layoutParams = imageview.getLayoutParams();
                        layoutParams.width = screenWidth;
                        layoutParams.height = screenHeight;
                        imageview.setLayoutParams(layoutParams);
                        imageview.setImageBitmap(resource);
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {

                    }
                });
        return rootview;
    }
}



